﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using CoreCms.Net.Configuration;
using CoreCms.Net.Filter;
using CoreCms.Net.IServices;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.Model.ViewModels.Basics;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Utility.Helper;
using CoreCms.Net.Web.Admin.Infrastructure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using SqlSugar;

namespace CoreCms.Net.Web.Admin.Controllers.Shop
{
    /// <summary>
    ///     日历签到设置
    /// </summary>
    [Description("日历签到设置")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    [RequiredErrorForAdmin]
    [Authorize(Permissions.Name)]
    public class CoreCmsCheckInController : ControllerBase
    {

        private readonly ICoreCmsSettingServices _coreCmsSettingServices;
        private readonly ICoreCmsUserGradeServices _coreCmsUserGradeServices;
        private readonly ICoreCmsContinuousCheckInRuleDetailsServices _coreCmsContinuousCheckInRuleDetailsServices;
        private readonly ICoreCmsContinuousCheckInRulesServices _coreCmsContinuousCheckInRulesServices;
        private readonly ICoreCmsCumulativeCheckInRulesServices _coreCmsCumulativeCheckInRulesServices;


        /// <summary>
        /// 构造函数
        /// </summary>
        public CoreCmsCheckInController(ICoreCmsSettingServices coreCmsSettingServices, ICoreCmsUserGradeServices coreCmsUserGradeServices, ICoreCmsContinuousCheckInRuleDetailsServices coreCmsContinuousCheckInRuleDetailsServices, ICoreCmsContinuousCheckInRulesServices coreCmsContinuousCheckInRulesServices, ICoreCmsCumulativeCheckInRulesServices coreCmsCumulativeCheckInRulesServices)
        {
            _coreCmsSettingServices = coreCmsSettingServices;
            _coreCmsUserGradeServices = coreCmsUserGradeServices;
            _coreCmsContinuousCheckInRuleDetailsServices = coreCmsContinuousCheckInRuleDetailsServices;
            _coreCmsContinuousCheckInRulesServices = coreCmsContinuousCheckInRulesServices;
            _coreCmsCumulativeCheckInRulesServices = coreCmsCumulativeCheckInRulesServices;
        }


        #region 首页数据============================================================
        // POST: Api/CoreCmsSetting/GetIndex
        /// <summary>
        /// 首页数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("首页数据")]
        public async Task<AdminUiCallBack> GetIndex()
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };
            var configs = await _coreCmsSettingServices.GetConfigDictionaries();
            var filesStorageOptionsType = EnumHelper.EnumToList<GlobalEnumVars.FilesStorageOptionsType>();
            var userGrade = await _coreCmsUserGradeServices.QueryAsync();

            //连续签到规则
            var continuousCheckInRules = await _coreCmsContinuousCheckInRulesServices.GetDataWidthChild();
            //制作新数据，防止出现


            JArray newDetails = new JArray();

            if (continuousCheckInRules.Any())
            {
                foreach (var item in continuousCheckInRules)
                {
                    JArray di = new JArray();
                    var newUserGrand = userGrade;
                    foreach (var itemGrade in newUserGrand)
                    {
                        JObject diItem = new JObject();
                        diItem.Add("grand", JObject.FromObject(itemGrade));
                        var details = item.details.Find(p => p.userGradeId == itemGrade.id);
                        if (details != null)
                        {
                            diItem.Add("details", JObject.FromObject(details));
                        }
                        di.Add(diItem);
                    }
                    newDetails.Add(di);
                }
            }




            //累计签到规则
            var cumulativeCheckInRules = await _coreCmsCumulativeCheckInRulesServices.QueryAsync(true, true);

            jm.data = new
            {
                configs,
                filesStorageOptionsType,
                userGrade,
                continuousCheckInRules,
                newDetails,
                cumulativeCheckInRules
            };

            return jm;
        }
        #endregion

        #region 保存提交============================================================
        // POST: Api/CoreCmsSetting/DoSave
        /// <summary>
        /// 保存提交
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("保存提交")]
        public async Task<AdminUiCallBack> DoSave([FromBody] FMCoreCmsSettingDoSaveModel model)
        {
            var jm = await _coreCmsSettingServices.UpdateAsync(model);
            return jm;
        }
        #endregion


        #region 保存累计签到规则============================================================
        // POST: Api/CoreCmsSetting/DoSave
        /// <summary>
        /// 保存累计签到规则
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("保存累计签到规则")]
        public async Task<AdminUiCallBack> DoSaveCumulativeCheckInRules([FromBody] FMDoSaveCumulativeCheckInRules entity)
        {
            var jm = new AdminUiCallBack();

            if (!entity.entity.Any())
            {
                jm.msg = "请提交数据";
                return jm;
            }

            //判断是否存在0天数或者0赠送
            var isHaveEnptyDaysOrNum = entity.entity.Count(p => p.days <= 0 || p.num <= 0);
            if (isHaveEnptyDaysOrNum > 0)
            {
                jm.msg = "累计签到天数或赠送数量不能为零";
                return jm;
            }

            //判断是否存在相同的天数设置。
            var isHave = entity.entity.GroupBy(i => i.days).Any(g => g.Count() > 1);
            if (isHave)
            {
                jm.msg = "存在相同的累计签到天数。请排查";
                return jm;
            }

            //先清理掉数据,因为是配置数据，可直接删除添加新的
            var doEnpty = await _coreCmsCumulativeCheckInRulesServices.DeleteAsync(p => p.id > 0, true);

            //插入新的数据
            var insertCount = await _coreCmsCumulativeCheckInRulesServices.InsertAsync(entity.entity, true);


            jm.code = 0;
            jm.msg = "保存成功";
            return jm;
        }
        #endregion

        #region 保存连续签到规则============================================================
        // POST: Api/CoreCmsSetting/DoSave
        /// <summary>
        /// 保存连续签到规则
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("保存连续签到规则")]
        public async Task<AdminUiCallBack> DoSaveContinuousCheckInRules([FromBody] FMDoSaveContinuousCheckInRules entity)
        {
            var jm = new AdminUiCallBack();

            if (entity.entity.Any()) return await _coreCmsContinuousCheckInRulesServices.InsertAsync(entity.entity);
            jm.msg = "请提交数据";
            return jm;

        }
        #endregion
    }
}
